<?php

declare(strict_types=1);

namespace App\Robot\Crontab;

use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChSeat;
use App\CustHub\Service\RobotLoginService;

class SeatCrontab
{
    public function execute(): string
    {
        ChSeat::query()
            ->where('status',1)
            ->where('seat_type',0)
            ->where('expire_time','<',time())
            ->chunkById(100,function ($seats){
                $seatIds = $seats->pluck('id')->toArray();
                ChSeat::query()->whereIn('id',$seatIds)->update(['status'=>2,'use_status' => 0]);

                $robotIdList = ChRobot::query()
                    ->whereIn('seat_id',$seatIds)
                    ->pluck('id')
                    ->toArray();

                foreach ($robotIdList as $robotId){
                    try {
                        container()->get(RobotLoginService::class)->loginOut(['id' => $robotId]);
                    }catch (\Throwable $e){
                        logger()->info('席位检测机器人退出登录失败'.$robotId.'----'.$e->getMessage());
                    }
                }
            });
        return '席位到期检测 successfully';
    }
}